from bs4 import BeautifulSoup
from .. import items
from datetime import date


# 输入文本内容 返回提取出的结果res_list 和标签集合 label_set
def resolve_content_all(cont, date_s):
    """调用不同时间段的函数进行解析"""
    cur_date = get_date_from_str(date_s)
    date_2019_2_21 = date(2019, 2, 21)
    print("date_s:%s" % date_s)
    if cur_date >= date_2019_2_21:
        return resolve_file_content2019(cont, date_s)
    else:
        return resolve_file_content2018_10_22p(cont, date_s)


# 2019-2-19
def get_date_from_str(date_s):
    dss = date_s.split("-")
    return date(int(dss[0]), int(dss[1]), int(dss[2]))


def resolve_file_content2019(cont, date_s):
    label_set = set()
    col_loc_dict = {2: '股票代码', 3: '名称'}
    # , 7: '涨停概念'
    res_list = []
    res_map = {}

    soup = BeautifulSoup(cont)

    for table in soup.select("table[class='table table-hover .table-sm']"):
        trs = table.tbody.findChildren()
        for tr in trs:
            tds = tr.findAll("td");  # findAll
            oneTP = items.TP_item()
            if len(tds) > 2:
                oneTP['code'] = tds[1].text;
                oneTP['name'] = tds[2].text;
            if (len(tds) > 6):
                oneTP['full_time'] = date_s;
                oneTP['full_res'] = format_str_quotes(tds[6].text)
                res_map[oneTP['code']] = oneTP
                label_set.update(split_str_quotes_blank(tds[6].text))
    print('res_map:%s' % res_map)
    res_list.extend(res_map.values())

    return label_set, res_list


def resolve_file_content2018_11_27p(cont, date_s):
    return resolve_file_content2018_10_22p(cont, date_s)


def resolve_file_content2018_10_22p(cont, date_s):
    label_set = set()
    # cont = ''
    res_list = []
    res_map = {}

    soup = BeautifulSoup(cont)
    # print(soup.select("table[class='m-table']"))
    tables = soup.select("table[class='m-table']")

    for index, table in enumerate(tables):
        # 单独处理最后一个table

        trs = table.tbody.findChildren()
        for tr in trs:
            tds = tr.findAll("td");
            t_labels = []
            added = False
            oneTP = items.TP_item()
            if len(tds) > 2:
                oneTP['code'] = tds[1].text;
                oneTP['name'] = tds[2].text;
                oneTP['full_time'] = date_s;

            if (index == len(tables) - 1):
                if (len(tds) > 12):
                    oneTP['full_res'] = format_str_quotes(tds[12].text)
                    t_labels = split_str_quotes_blank(tds[12].text)
                    added = True
            else:
                if (len(tds) > 14):
                    oneTP['full_res'] = format_str_quotes(tds[14].text)
                    t_labels = split_str_quotes_blank(tds[14].text)
                    added = True
            if added:
                res_map[oneTP['code']] = oneTP
                # res_set.append(oneTP)
                label_set.update(t_labels)
    res_list.extend(res_map.values())

    print("one label_set %s ; one res:%s" % (label_set, res_list))
    return label_set, res_list


def split_str_quotes_blank(str):
    strs_res = set()
    for quotes_split in str.split(";"):
        quotes_split == quotes_split.strip();
        for blank_split in quotes_split.split(" "):
            blank_split = blank_split.strip();
            if not len(blank_split) == 0:
                strs_res.add(blank_split)
    return strs_res


def format_str_quotes(str):
    str_res = ""
    return str.replace(";", ",").replace(" ", ",")

# if __name__ == "__main__":
#     print(split_str_quotes_blank("	华为;OLED ;"))
#     ls, rl = resolve_file_content2018_10_22p("", " ")
#     print("标签集合:", ls)
#     print("结果:", rl)


# base_path = '/html/body/div[2]/font/div[1]';
# cell_path = base_path + '/table/tbody/tr[1]/td[1]/text()';

# while not len(root.xpath(cell_path))==0:
# cell = root.xpath(cell_path).extract()[0];

# cell_path = base_path + '/table/tbody/tr[1]/td[1]/span/text()';
# for key in col_loc_dict:
#     f=cell_path.find('td[')
#     cell_path = cell_path[:f+len("td['")-1]+str(key)+cell_path[f+len("td['"):]
#     print('path:'+cell_path)
#     cell_val_not = root.xpath(cell_path);
#
#     if len(cell_val_not) == 0:
#         cell_path = base_path + '/table/tbody/tr[1]/td[1]/text()';
#         f = cell_path.find('td[')
#         cell_path = cell_path[:f + len("td['") - 1] + str(key) + cell_path[f + len("td['"):]
#         print('path:' + cell_path)
#
#         cell_val_not = root.xpath(cell_path);
#     if not len(cell_val_not)==0:
#         cell_val = cell_val_not.extract()[0];
#         print(cell_val)
#         res_list.append({col_loc_dict[key]:cell_val})
#

# base_path = compact(base_path,'font','font/')
# f = base_path.find("font");
# base_path = base_path[:f]+'font/'+base_path[f:]
# print('bp:'+base_path)
#
# print(res_list)
# cell = root.xpath(cell_path).extract()[0];
# print(cell)

# ztyy = "军工;股权转让;实控人变更;"
# ztyyr = ztyy.split(";")[:-1]
# print(ztyyr)

# 更新label 集合
# label_set.update(ztyyr)
# print(label_dict)

# print(cell)
